#!/usr/bin/env python
# encoding: utf-8
from utils.common import *
from feature_set.base_feature import BaseFeature, RequstData


class UiUnBaseV2(BaseFeature):
    def __init__(self):
        super().__init__()
        self.function_map = {
            'user_info1': self.gen_user_info1_feature
        }
        self.province_map = None

    def load_conf(self):
        """
        load config file
        Returns:

        """
        pass

    def load_request(self, request_data: RequstData):
        """
        get request data and format feature input data
        Args:
            request_data: input detail data

        Returns:
            format user_info
        """

        self.data = request_data.data_sources['user_info_1']

    def gen_user_info1_feature(self):
        user_info1_features = {'user_age': -999,
                               'id_card_type': -999,
                               'user_education_level': -999,
                               'user_marriage_status': -999,
                               'user_home_province': -999,
                               'user_work_years': -999,
                               'user_gender': -999,
                               'user_first_name_len': -999,
                               'user_mid_name_len': -999,
                               'user_last_name_len': -999,
                               'user_email_type': -999,
                               'user_salary_pay_frequency': -999,
                               'user_work_type': -999,
                               'user_month_income': -999,
                               'user_line_account_len':-999,
                               'user_line_account_letter_len':-999,
                               'user_line_account_digit_len':-999,
                               'user_line_account_symbol_len':-999,
                               'user_register_fill_timediff': -999,
                               'user_register_order_timediff': -999,
                               'user_fill_order_timediff': -999,
                               'user_first_contact_relationship': -999,
                               'user_second_contact_relationship': -999,
                               'user_first_contact_name_len': -999,
                               'user_second_contact_name_len': -999
                               }

        if type(self.data) is not dict:
            self.logger.error('user_info节点数据不是dict类型！')
            return user_info1_features

        user_record = self.data['userInfo']['userRecord']
        if type(user_record) is not dict:
            self.logger.error('userRecord节点数据不是dict类型！')
            return user_info1_features

        user_age = user_record['age']
        id_card_type = int(user_record['idCardNumber'][0])
        user_education_level = user_record['educationLevel']
        user_marriage_status = user_record['marriageStatus']
        try:
            user_home_province = user_record['homeProvince']
            user_home_province = self.province_map[user_home_province]
        except:
            user_home_province = -999
        user_work_years = user_record['workYears']
        user_gender = user_record['gender']
        user_first_name_len = len(user_record['firstName'])
        user_mid_name_len = len(user_record['middleName'])
        user_last_name_len = len(user_record['lastName'])

        user_email_type = get_email_type(user_record['email'])
        user_salary_pay_frequency = user_record['salaryPayFrequency']
        user_work_type = user_record['workType']
        user_month_income = user_record['monthlyIncome']
        if 'lineAccount' in user_record and user_record['lineAccount']:
            user_line_account_len = len(user_record['lineAccount'])
            user_line_account_letter_len = len(re.findall(r'[a-zA-Z]', user_record['lineAccount']))
            user_line_account_digit_len = len(re.findall(r'\d', user_record['lineAccount']))
            user_line_account_symbol_len = len(re.findall(r'[^a-zA-Z\d]', user_record['lineAccount']))
        else:
            user_line_account_len = -999
            user_line_account_letter_len = -999
            user_line_account_digit_len = -999
            user_line_account_symbol_len = -999

        register_time = datetime.strptime(user_record['registerTime'], "%Y-%m-%d %H:%M:%S")
        fill_time = datetime.strptime(user_record['createTime'], "%Y-%m-%d %H:%M:%S")
        user_register_fill_timediff = (fill_time - register_time).total_seconds() / 3600
        if self.data['productInfo'] and self.data['productInfo']['createTime']:
            order_apply_time = datetime.strptime(self.data['productInfo']['createTime'], "%Y-%m-%d %H:%M:%S")
            user_register_order_timediff = (order_apply_time - register_time).total_seconds() / 3600
            user_fill_order_timediff = (order_apply_time - fill_time).total_seconds() / 3600
        else:
            user_register_order_timediff = -999
            user_fill_order_timediff = -999

        contact_info = self.data['userInfo']['userContactInfo']
        contact_info.sort(key=lambda s: s["contactPhoneNumber"])
        try:
            user_first_contact_relationship = contact_info[0]['contactRelationship']
            user_second_contact_relationship = contact_info[1]['contactRelationship']
            user_first_contact_name_len = len(contact_info[0]['contactName'])
            user_second_contact_name_len = len(contact_info[1]['contactName'])
        except:
            user_first_contact_relationship = -999
            user_second_contact_relationship = -999
            user_first_contact_name_len = -999
            user_second_contact_name_len = -999

        user_info1_features = {'user_age': int(user_age),
                               'id_card_type': id_card_type,
                               'user_education_level': int(user_education_level),
                               'user_marriage_status': int(user_marriage_status),
                               'user_home_province': int(user_home_province),
                               'user_work_years': int(user_work_years),
                               'user_gender': int(user_gender),
                               'user_first_name_len': user_first_name_len,
                               'user_mid_name_len': user_mid_name_len,
                               'user_last_name_len': user_last_name_len,
                               'user_email_type': user_email_type,
                               'user_salary_pay_frequency': user_salary_pay_frequency,
                               'user_work_type': user_work_type,
                               'user_month_income': user_month_income,
                               'user_line_account_len':user_line_account_len,
                               'user_line_account_letter_len':user_line_account_letter_len,
                               'user_line_account_digit_len':user_line_account_digit_len,
                               'user_line_account_symbol_len':user_line_account_symbol_len,
                               'user_register_fill_timediff': user_register_fill_timediff,
                               'user_register_order_timediff': user_register_order_timediff,
                               'user_fill_order_timediff': user_fill_order_timediff,
                               'user_first_contact_relationship': int(user_first_contact_relationship),
                               'user_second_contact_relationship': int(user_second_contact_relationship),
                               'user_first_contact_name_len': user_first_contact_name_len,
                               'user_second_contact_name_len': user_second_contact_name_len
                               }

        return user_info1_features
